package fr.web325.servlet.api.user;

import fr.web325.bean.Json;
import fr.web325.bean.User;
import fr.web325.dao.UserDao;
import fr.web325.utils.CodeUtils;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/api/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        * | username  | 用户名 | 不能为空 |
            | --------- | ------ | -------- |
            | PASSWORD  | 密码   | 不能为空 |
            | gender    | 性别   | 不能为空 |
            | email     | 邮箱   | 不能为空 |
            | telephone |        |          |
        * */
        User user = new User();
        try {
            BeanUtils.populate( user,req.getParameterMap());
            System.out.println(user.toString());
            String username = req.getParameter("username");
            user.setRole("普通用户");
            user.setRegistTime(new Date());
            user.setIntroduce("");
            String code = new CodeUtils().getActiveCode(username);
            user.setActiveCode(code);
            String msg = new UserDao().addUser(user);
            if(msg.equals("注册成功")){
                // 激活链接
                String ActiveUrl = req.getContextPath()+"/shop/client/activation?ActivationCode="+code;
                JSONObject json = new Json(201,null,msg).getRespJson();
                json.put("ActiveUrl",ActiveUrl);
                resp.getWriter().print(json);
            }else{
                resp.getWriter().print(new Json(200,null,msg).getRespJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
